// api/handlers/ai_handler.go
package handlers

import (
	"encoding/json"
	"log"
	"mygin/internal/services"
	"mygin/pkg/gummy"
	"mygin/pkg/response"
	"mygin/pkg/ws"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// 全局 WebSocket 升级器
var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true // 生产环境应该验证来源
	},
}

type AiHandler struct {
	// 可以在这里添加一些简单的依赖，如配置等
	aliyService *services.AliyService
}

func NewAiHandler(aliyService *services.AliyService) *AiHandler {
	return &AiHandler{
		aliyService: aliyService,
	}
}

func (h *AiHandler) Ai(c *gin.Context) {
	decryptedData, exists := c.Get("decryptedData")
	if !exists {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "data processing failed"})
		return
	}

	c.JSON(http.StatusOK, response.Success("ok", decryptedData))
}

func (h *AiHandler) AiChat(c *gin.Context) {
	var request struct {
		Content string `json:"content"`
	}

	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, response.Fail(http.StatusBadRequest, "invalid request"))
		return
	}

	if request.Content == "" {
		c.JSON(http.StatusBadRequest, response.Fail(http.StatusBadRequest, "content cannot be empty"))
		return
	}
	ok, err := h.aliyService.AiChat(request.Content)
	if err != nil {
		// 处理错误
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, response.Success("ai", ok))
}

// func (h *AiHandler) Gummy(c *gin.Context) {
// 	apiKey := "sk-8a4ec2f9f80d433eb6a85747e951f1c6"
// 	// 连接WebSocket服务
// 	conn, err := gummy.ConnectWebSocket(apiKey)
// 	if err != nil {
// 		log.Fatal("连接WebSocket失败：", err)
// 	}
// 	defer gummy.CloseConnection(conn)

// 	// 创建通道
// 	taskStarted := make(chan bool)
// 	results := make(chan gummy.TranslationResult)

// 	// 启动结果接收器
// 	gummy.StartResultReceiver(conn, taskStarted, results)

// 	// 启动一个goroutine来接收结果
// 	// taskStarted := make(chan bool)
// 	// taskDone := make(chan bool)
// 	// gummy.StartResultReceiver(conn, taskStarted, taskDone)

// 	// 发送run-task指令
// 	taskID, err := gummy.SendRunTaskCmd(conn)
// 	if err != nil {
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送run-task指令失败"})
// 		return
// 	}

// 	// 等待task-started事件
// 	gummy.WaitForTaskStarted(taskStarted)

// 	// 发送待识别音频文件流
// 	if err := gummy.SendAudioData(conn); err != nil {
// 		log.Fatal("发送音频失败：", err)
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送音频失败"})
// 		return
// 	}

// 	// 发送finish-task指令
// 	if err := gummy.SendFinishTaskCmd(conn, taskID); err != nil {
// 		log.Fatal("发送finish-task指令失败：", err)
// 		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送finish-task指令失败"})
// 		return
// 	}
// 	// 等待并获取最终结果
// 	result := <-results
// 	// 返回结果给客户端
// 	c.JSON(http.StatusOK, gin.H{
// 		"status": "success",
// 		"result": result,
// 	})

// }

func (h *AiHandler) Gummy(c *gin.Context) {
	// 升级HTTP连接到WebSocket
	upgrader := websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true // 允许所有跨域请求，生产环境应更严格
		},
	}

	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("WebSocket升级失败:", err)
		return
	}
	defer ws.Close()

	apiKey := "sk-8a4ec2f9f80d433eb6a85747e951f1c6"
	// 连接WebSocket服务
	conn, err := gummy.ConnectWebSocket(apiKey)
	if err != nil {
		log.Println("连接WebSocket失败:", err)
		ws.WriteMessage(websocket.TextMessage, []byte(`{"error": "连接后端服务失败"}`))
		return
	}
	defer gummy.CloseConnection(conn)

	// 创建通道
	taskStarted := make(chan bool)
	results := make(chan gummy.TranslationResult)
	done := make(chan struct{})

	// 启动结果接收器
	go gummy.StartResultReceiver(conn, taskStarted, results, done)

	// 发送run-task指令
	taskID, err := gummy.SendRunTaskCmd(conn)
	if err != nil {
		log.Println("发送run-task指令失败:", err)
		ws.WriteMessage(websocket.TextMessage, []byte(`{"error": "发送任务指令失败"}`))
		return
	}

	// 等待task-started事件
	gummy.WaitForTaskStarted(taskStarted)

	// 发送待识别音频文件流
	if err := gummy.SendAudioData(conn); err != nil {
		log.Println("发送音频失败:", err)
		ws.WriteMessage(websocket.TextMessage, []byte(`{"error": "发送音频数据失败"}`))
		return
	}

	// 发送finish-task指令
	if err := gummy.SendFinishTaskCmd(conn, taskID); err != nil {
		log.Println("发送finish-task指令失败:", err)
		ws.WriteMessage(websocket.TextMessage, []byte(`{"error": "结束任务指令失败"}`))
		return
	}

	// 持续监听结果并转发给客户端
	for {
		select {
		case result := <-results:
			// 将结果转换为JSON并发送给客户端
			jsonResult, err := json.Marshal(result)
			if err != nil {
				log.Println("JSON编码失败:", err)
				continue
			}

			if err := ws.WriteMessage(websocket.TextMessage, jsonResult); err != nil {
				log.Println("发送消息到客户端失败:", err)
				return
			}

			// 如果是最终结果，关闭连接
			if result.IsFinal {
				return
			}

		case <-done:
			// 结果接收器已完成
			return

		case <-c.Request.Context().Done():
			// 客户端断开连接
			return
		}
	}
}

var managerInstance *ws.WebSocketManager
var once sync.Once

func GetWebSocketManager() *ws.WebSocketManager {
	once.Do(func() {
		managerInstance = ws.NewWebSocketManager()
	})
	return managerInstance
}

// connectWebSocket 处理WebSocket连接
func (h *AiHandler) ConnectWebSocket(c *gin.Context) {
	userID := c.Param("userID")
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Printf("Failed to upgrade to websocket: %v", err)
		return
	}
	GetWebSocketManager().RegisterClient(userID, conn)
}

// sendMessage 处理发送消息请求
func (h *AiHandler) SendMessage(c *gin.Context) {
	var msg struct {
		Sender    string `json:"sender"`
		Recipient string `json:"recipient"`
		Content   string `json:"content"`
	}

	if err := c.ShouldBindJSON(&msg); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	GetWebSocketManager().SendMessageToUser(msg.Sender, msg.Recipient, msg.Content)

	c.JSON(http.StatusOK, gin.H{"status": "message sent"})
}
